<script setup lang="ts">
import { ref,reactive,onMounted} from 'vue'
import { getCaptcha, login,checkCaptcha,sendEmail, register, getMenu } from '@/api'
import { setAccessToken,error, success, warning } from '@/utils'
import { useRouter } from 'vue-router';
import type { FormInstance } from 'element-plus';
import {useUserStore} from '@/stores'

const userStore = useUserStore();
const router = useRouter();
//表单状态切换
const form_state = ref(0);
const captcha = ref('');
const uriCount = ref(0);
const captchaUri = ref("http://localhost:8080/public/getCaptcha?uriCount=");
const loginForm = ref<FormInstance>();
const registerForm = ref<FormInstance>();
const sendButton = ref(false);
const count_time = ref('获取验证码');
const loading = ref(false);


//登录表单验证
interface checkForm {
  username: string;
  password: string;
  confirmPassword: string;
  email: string;
  code: string;
}

//登录，注册表单数据
const form = reactive<checkForm>({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  code: ''
})


const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 32, message: '长度在 3 到 32 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 20, message: '长度在 8 到 20 个字符', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '长度为4-6个字符', trigger: 'blur' }
  ]
}

onMounted(() => {
  findCaptcha();
})

const findCaptcha = () => {
  uriCount.value = uriCount.value + 1;
  captchaUri.value = "http://localhost:8080/public/getCaptcha?uriCount=" + uriCount.value;

}

//登录
const theLogin = () => {
  const formData = new FormData();
  formData.append('username', form.username);
  formData.append('password', form.password);
  login(formData).then(({ data }) => {
    console.log(data)
    if(data){
      success("登录成功");
      setAccessToken(data);
      userStore.username = form.username;
      userStore.loadUserStore()
      clearForm();
      router.push('/');
    }else {
      error("登录失败");
    }
  })
}



const onSubmit = async () => {
  let verify_code = await verify();

  if(verify_code){
    checkCaptcha(form.code).then( (res:any) =>{
      if(res.code === 2000 && res.data === true){
        theLogin();
      }else{
        error("验证码错误");
        findCaptcha();
      }
    })
  }else {
    error("请检查输入信息")
  }
};

const testLogin=()=>{
  if(localStorage.getItem("MALL_AUTH_TOKEN")==="" || localStorage.getItem("MALL_AUTH_TOKEN")===null){
    userStore.state=true;
  }
}

//验证表单是否正确
const verify = async () => {
  let submit = false;
  if(loginForm.value){
    submit = await loginForm.value.validate((valid:boolean) => {
      return valid;
    });
  }
  if(!submit && registerForm.value){
    submit = await registerForm.value.validate((valid:boolean) => {
      return valid;
    });
  }
  return submit;
}

//清除表单内容
const clearForm = () => {
  form.username = '';
  form.password = '';
  form.confirmPassword = '';
  form.email = '';
  form.code = '';
}

//发送邮件
const sendEmails = async ()=>{
  if(form.email === ''|| form.username===''|| form.password===''){
    error("请检查输入信息");
    return;
  }else {
    disableButton()
  }
  if(form.password!==form.confirmPassword){
    error("两次密码不一致");
    return;
  }
  await sendEmail({email:form.email}).then((res:any) => {
    if(res.code === 2000){
      success("验证码发送成功,请稍等");
    }else{
      error("验证码发送失败,请重新发送");
    }
  })
}

//发送成功按钮保护倒计时
const disableButton = () => {
  sendButton.value = true;
  const killTime = ref(60);

  const timer = setInterval(() => {
    killTime.value = killTime.value - 1;
    if(killTime.value < 0){
      count_time.value = '获取验证码';
      sendButton.value = false;
      clearInterval(timer);
    }else {
      count_time.value = '请稍等('+ killTime.value + ')';
    }
  }, 1000)
}

const userRegister = async () => {
  let submit = await verify();
  loading.value = true;
  if(submit){
    await register({
      username:form.username,
      password:form.password,
      email:form.email,
      code:form.code
    }).then((res:any) => {
      if(res.code === 2000&& res.data){
        success("注册成功");
        clearForm();
      }else if(res.msg==="验证码已过期"){
        warning("验证码已过期,请重新发送")
      }else {
          error("注册失败,请重试");
      }
    })
  }
  loading.value = false;
}

//返回登陆界面
const toLogin = () => {
  form_state.value = 0;
  clearForm()
}

const toRegister = () => {
  form_state.value = 1;
  clearForm()
}

</script>

<template>
  <transition name="el-zoom-in-center">
    <div class="login-container">
    <transition name="el-zoom-in-center">
    <el-form label-position="right"
             ref="loginForm"
            label-width="auto"
            :model="form"
            :rules="rules"
             class="form_class"
             v-if="form_state===0"
            hide-required-asterisk>
      <h1 style="text-align: center;margin:15px;">登录</h1>
      <el-form-item label="用户名:" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名或邮箱"/>
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input v-model="form.password" placeholder="密码" type="password"/>
      </el-form-item>
      <el-form-item label="验证码:" prop="code" >
        <el-input v-model="form.code" placeholder="验证码" style="width: 50%;"/>
        <img :src="captchaUri" style="width: 45%;border-radius: 10px;margin-left: 10px;" @click="findCaptcha"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">登录</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"  @click="toRegister" style="margin-left: 85%;color: black;">-->注册</el-button>
      </el-form-item>
  </el-form>
    </transition>

    <transition name="el-zoom-in-center">
    <el-form label-position="right"
             ref="registerForm"
             label-width="auto"
             :model="form"
             :rules="rules"
             class="form_class"
             v-if="form_state===1"
              hide-required-asterisk>
      <h1 style="text-align: center;margin:10px;">注册</h1>
      <el-form-item label="用户名:" prop="username">
        <el-input v-model="form.username" placeholder="用户名" />
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input v-model="form.password" placeholder="密码" />
      </el-form-item>
      <el-form-item label="确认密码:" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" type="password" placeholder="确认密码" />
      </el-form-item>
      <el-form-item label="邮箱:" prop="email">
        <el-input v-model="form.email" placeholder="邮箱" />
      </el-form-item>
      <el-form-item label="验证码:" prop="code" >
        <el-input v-model="form.code" placeholder="获取验证码" style="width: 50%;"/>
        <el-button @click="sendEmails" :disabled="sendButton" type="primary" style="width: 30%;margin-left: 5%;">{{count_time}}</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="userRegister" :loading="loading">注册</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="toLogin" style="margin-left: 85%;color: black;">登录<--</el-button>
      </el-form-item>
    </el-form>
    </transition>
  </div>
  </transition>
</template>

<style scoped>
    .login-container {
      width: 100%;
      height: 100vh;
      min-width: 1250px;
      background: url("@/assets/img/login.jpg") no-repeat center center;
      background-size: 100% 100%;
    }

    .form_class {
      padding:0 15px;
      border-radius: 10px;
      background-color: rgba(255, 255, 255, 0.2);
      width: 430px;
      height: auto;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    .el-form-item {
      max-width: 400px;
    }

    ::v-deep .el-form-item__label{
      color: black;
      font-weight: bolder;
    }

    .el-button {
      margin-left: 25%;
      width: 50%;
    }
</style>